<template>
  <div>
    <MyTable :arr="list">
      <template #head>
        <th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>
      <!-- 渲染 -->
      <template v-slot:body="scope">
        <td>{{scope.row.id}}</td>
        <td>{{scope.row.goods_name}}</td>
        <td>{{scope.row.goods_price}}</td>
        <td>
          <!-- v-if 和v-else 和设置各种点击事件 -->
          <input class="tag-input form-control" style="width: 100px;" type="text" v-if="scope.row.inputVisible" 
         v-focus @blur="num===0?scope.row.inputVisible = false:scope.row.inputVisible = true" v-model="scope.row.inputValue" @keydown.enter="addrags(scope.row)"
         />
          <button v-else style="display: block;" class="btn btn-primary btn-sm add-tag"
            @click="scope.row.inputVisible = true">+Tag</button>
          <span class="badge badge-warning" v-for="(item,index) in scope.row.tags" :key="index">{{item}}</span>
        </td>
        <td>
          <button class="btn btn-danger btn-sm" @click="delbtn(scope.row.id)">删除</button>
        </td>
      </template>
    </MyTable>
  </div>
</template>

<script>
import MyTable from "../components/MyTable";

export default {
  components: {
    MyTable,
  },
  data() {
    return {
      list: [],// 所有数据
      num:0
    };
  },
  //获取数据
  async created() {
    const { data: { data: res } } = await this.$axios({
      url: "/api/goods",
    })
    this.list = res
  },
  methods: {
    delbtn(id) {
      this.list = this.list.filter(item => item.id !== id)
    },
    addrags(val){
      if(val.inputValue.trim()===''){
        this.num++
        return  alert('输入不正确')  
      } 
      val.tags.push(val.inputValue)
      val.inputValue=''
      val.inputVisible = false
      this.num=0
    }
  },
  directives: {
    focus:{
      inserted(el){
        el.focus()
      }
    }
  }
};
</script>
 
<style>
.badge-warning {
  margin-right: 10px;
}
</style>